package com.ayh.campusfun.common.core.interceptor;


import com.ayh.campusfun.common.core.jwt.JWTUtils;
import com.ayh.campusfun.common.exception.http.ForbiddenException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @author ayh
 * @create 2021/3/24 0024 12:38
 * JWT处理类
 */

//实现HandlerInterceptor，重写preHandle方法（在所有请求前执行）
public class JWTInterceptor implements HandlerInterceptor {

    @Value("${jwt.token-header}")
    private String toKenHeader;

    @Value("${jwt.token-head}")
    private String toKenHead;

    @Autowired
    private JWTUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            System.out.println("OPTIONS请求，放行");
            return true;
        }
        String authorization = request.getHeader(toKenHeader);
        if (null == authorization) {
            throw new ForbiddenException(60009);
        }
        String token = authorization.replaceAll(toKenHead,"").trim();
//        验证token是否有效
        jwtUtils.verifyToken(token);
        Date expiredDateFromToken = jwtUtils.getExpiredDateFromToken(token);
        Date date = new Date();
        if (expiredDateFromToken.getTime() - date.getTime() < 60 * 60 * 24 * 1000){
            response.setHeader("refresh", "true");
        }else {
            response.setHeader("refresh", "false");
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
